<?php

namespace app\api\model;

use think\Model;

class Product extends BaseModel
{

    protected $hidden = [ 'delete_time', 'update_time', 'create_time', 'from', 'pivot', 'img_id', 'category_id', ];

    /**
     * 获取某分类下商品
     * @param $categoryID
     * @param int $page
     * @param int $size
     * @param bool $paginate
     * @return \think\Paginator
     */
    public static function getProductsByCategoryID(
    $categoryID, $paginate = true, $page = 1, $size = 30)
    {
        $query = self::
                where('category_id', '=', $categoryID);
        if (!$paginate)
        {
            return $query->select();
        }
        else
        {
            // paginate 第二参数true表示采用简洁模式，简洁模式不需要查询记录总数
            return $query->paginate(
                            $size, true, [
                        'page' => $page
            ]);
        }
    }

    public function getMainImgUrlAttr($value, $data)
    {
        return $this->prefixImgUrl($value, $data);
    }


    public static function getMostRecent($count)
    {
        $res = self::limit($count)
        ->order('create_time desc')
        ->select();
        return $res;
    }

    public static function getProductDetail($id)
    {
        $res = self::with([ 'imgs' => function($query) {
                        $query->order('order asc')
                        ->with('img');
                    } ])
                ->find($id);
        return $res;
    }

    public function imgs()
    {
        return $this->hasMany('ProductImage', 'product_id', 'id');
    }

}
